/**
 * 
 */
package persistence;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;

/**
 * @author hozakan
 *
 */
public class ConnectionManager {

	private static ConnectionManager instance;
	private static final Logger logger = Logger.getLogger(ConnectionManager.class);
	
	private Connection cnx;
	
	private ResourceBundle res;
	
	public static ConnectionManager getInstance() throws ClassNotFoundException {
		if (instance == null)
			instance = new ConnectionManager();
		return instance;
	}
	
	private ConnectionManager() throws ClassNotFoundException {
		try {
			res = ResourceBundle.getBundle("resources/configPersis");
			Class.forName(res.getString("driverName"));
		} catch (ClassNotFoundException e) {
			logger.error("Le driver n'a pas été trouvé.");
			throw e;
		}
	}
	
	private void connexion() throws SQLException {
		try {
			cnx = DriverManager.getConnection(res.getString("BDD"), res.getString("user"), res.getString("password"));
		} catch (Exception e) {
			logger.error("Erreur de connexion");
		}
	}
	
	public Connection getConnection() throws SQLException {
		if (cnx == null || cnx.isClosed())
			connexion();
		return cnx;
	}
	
}
